package sixthDay;

import java.util.HashMap;

public class MinWindow {
    public String minWindow(String s, String t) {
        char[] sou = s.toCharArray();
        char[] tar = t.toCharArray();
        HashMap<Character, Integer> needs = new HashMap<>();
        HashMap<Character, Integer> window = new HashMap<>();
        int valid = 0;
        int left = 0, right = 0;
        int start = 0, len = Integer.MAX_VALUE;
        for(char c : tar){
            needs.put(c, needs.getOrDefault(c, 0) + 1);
        }
        while(right < sou.length){
            char c = sou[right];
            right++;
            if(needs.containsKey(c)){
                window.put(c, window.getOrDefault(c, 0) + 1);
                if(window.get(c).equals(needs.get(c))){
                    valid++;
                }
            }
            while(valid == needs.size()){
                if(right - left < len){
                    start = left;
                    len = right - left;
                }
                char d = sou[left];
                left++;
                if(needs.containsKey(d)){
                    window.put(d, window.get(d) - 1);
                    if(window.get(d) < Integer.valueOf(needs.get(d))){
                        valid--;
                    }
                }
            }
        }
        return len == Integer.MAX_VALUE ? "" : s.substring(start, start + len);
    }
}
